package com.csii.modules.online.cgreport.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csii.autopoi.poi.excel.ExcelExportUtil;
import com.csii.autopoi.poi.excel.entity.ExportParams;
import com.csii.autopoi.poi.excel.entity.params.ExcelExportEntity;
import com.csii.core.annotation.PermissionData;
import com.csii.core.api.Result;
import com.csii.core.exception.AppException;
import com.csii.core.system.vo.DictModel;
import com.csii.core.system.vo.DynamicDataSourceModel;
import com.csii.core.util.BrowserUtils;
import com.csii.core.util.oConvertUtils;
import com.csii.modules.online.cgreport.entity.OnlCgreportHead;
import com.csii.modules.online.cgreport.entity.OnlCgreportItem;
import com.csii.modules.online.cgreport.entity.OnlCgreportParam;
import com.csii.modules.online.cgreport.mapper.OnlCgreportHeadMapper;
import com.csii.modules.online.cgreport.service.IOnlCgreportHeadService;
import com.csii.modules.online.cgreport.service.IOnlCgreportItemService;
import com.csii.modules.online.cgreport.service.IOnlCgreportParamService;
import com.csii.modules.online.cgreport.util.DBSqlUtil;
import com.csii.modules.system.service.ISysBaseAPI;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;

@RestController("onlCgreportAPI")
@RequestMapping({"/online/cgreport/api"})
public class OnlCgreportAPI {
	private static final Logger a = LoggerFactory.getLogger(OnlCgreportAPI.class);
	@Autowired
	private IOnlCgreportHeadService onlCgreportHeadService;
	@Autowired
	private IOnlCgreportItemService onlCgreportItemService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IOnlCgreportParamService onlCgreportParamService;

	/**
	 * @param code
	 * @param req
	 * @return
	 */
	@GetMapping({"/getColumnsAndData/{code}"})
	@PermissionData
	public Result<?> getColumnsAndData(@PathVariable("code") String code, HttpServletRequest req) {
		OnlCgreportHead onlCgreportHead = (OnlCgreportHead) this.onlCgreportHeadService.getById(code);
		if (onlCgreportHead == null) {
			return Result.error("实体不存在");
		} else {
			Result result = this.getData(code, req);
			if (result.getCode().equals(200)) {
				JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(result.getResult()));
				JSONArray records = jsonObject.getJSONArray("records");
				QueryWrapper wrapper = new QueryWrapper();
				((QueryWrapper) ((QueryWrapper) wrapper.eq("cgrhead_id", code)).eq("is_show", 1)).orderByAsc("order_num");
				List list = this.onlCgreportItemService.list(wrapper);
				HashMap hashMap = new HashMap();
				//
				JSONArray var10 = new JSONArray();
				JSONArray var11 = new JSONArray();
				Iterator iter = list.iterator();

				while (iter.hasNext()) {
					OnlCgreportItem one = (OnlCgreportItem) iter.next();
					JSONObject object = new JSONObject(4);
					object.put("title", one.getFieldTxt());
					object.put("dataIndex", one.getFieldName());
					object.put("align", "center");
					object.put("sorter", "true");
					String var15;
					if (StringUtils.isNotBlank(one.getFieldHref())) {
						var15 = "fieldHref_" + one.getFieldName();
						JSONObject var16 = new JSONObject();
						var16.put("customRender", var15);
						object.put("scopedSlots", var16);
						JSONObject var17 = new JSONObject();
						var17.put("slotName", var15);
						var17.put("href", one.getFieldHref());
						var10.add(var17);
					}

					var11.add(object);
					var15 = one.getDictCode();
					List var19 = this.getDictList(var15, records, one.getFieldName());
					if (var19 != null) {
						hashMap.put(one.getFieldName(), var19);
						object.put("customRender", one.getFieldName());
					}
				}

				HashMap data = new HashMap(3);
				data.put("data", result.getResult());
				data.put("columns", var11);
				data.put("dictOptions", hashMap);
				data.put("fieldHrefSlots", var10);
				data.put("cgreportHeadName", onlCgreportHead.getName());
				return Result.ok(data);
			} else {
				return result;
			}
		}
	}

	/**
	 * getDictList 获取字典列表：
	 *
	 * @param str
	 * @param var2
	 * @param var3
	 * @return
	 */
	private List<DictModel> getDictList(String str, JSONArray var2, String var3) {
		List dictList = null;
		if (oConvertUtils.isNotEmpty(str)) {
			if (str.trim().toLowerCase().indexOf("select ") == 0 && (var3 == null || var2.size() > 0)) {
				str = str.trim();
				int var5 = str.lastIndexOf(";");
				if (var5 == str.length() - 1) {
					str = str.substring(0, var5);
				}

				String var6 = "SELECT * FROM (" + str + ") temp ";
				String var12;
				if (var2 != null) {
					ArrayList var7 = new ArrayList();

					for (int var8 = 0; var8 < var2.size(); ++var8) {
						JSONObject var9 = var2.getJSONObject(var8);
						String var10 = var9.getString(var3);
						if (StringUtils.isNotBlank(var10)) {
							var7.add(var10);
						}
					}

					var12 = "'" + StringUtils.join(var7, "','") + "'";
					var6 = var6 + "WHERE temp.value IN (" + var12 + ")";
				}

				List var11 = ((OnlCgreportHeadMapper) this.onlCgreportHeadService.getBaseMapper()).executeSelete(var6);
				if (var11 != null && var11.size() != 0) {
					var12 = JSON.toJSONString(var11);
					dictList = JSON.parseArray(var12, DictModel.class);
				}
			} else {
				dictList = this.sysBaseAPI.queryDictItemsByCode(str);
			}
		}

		return dictList;
	}

	/**
	 * @deprecated
	 */
	@Deprecated
	@GetMapping({"/getColumns/{code}"})
	public Result<?> getColumns(@PathVariable("code") String code) {
		OnlCgreportHead one = (OnlCgreportHead) this.onlCgreportHeadService.getById(code);
		if (one == null) {
			return Result.error("实体不存在");
		} else {
			QueryWrapper wrapper = new QueryWrapper();
			wrapper.eq("cgrhead_id", code);
			wrapper.eq("is_show", 1);
			wrapper.orderByAsc("order_num");
			List list = this.onlCgreportItemService.list(wrapper);
			ArrayList var5 = new ArrayList();
			HashMap var6 = new HashMap();
			Iterator var7 = list.iterator();

			while (var7.hasNext()) {
				OnlCgreportItem var8 = (OnlCgreportItem) var7.next();
				HashMap var9 = new HashMap(3);
				var9.put("title", var8.getFieldTxt());
				var9.put("dataIndex", var8.getFieldName());
				var9.put("align", "center");
				var9.put("sorter", "true");
				var5.add(var9);
				String var10 = var8.getDictCode();
				if (oConvertUtils.isNotEmpty(var10)) {
					List var11 = null;
					if (var10.toLowerCase().indexOf("select ") == 0) {
						List var12 = ((OnlCgreportHeadMapper) this.onlCgreportHeadService.getBaseMapper()).executeSelete(var10);
						if (var12 != null && var12.size() != 0) {
							String var13 = JSON.toJSONString(var12);
							var11 = JSON.parseArray(var13, DictModel.class);
						}
					} else {
						var11 = this.sysBaseAPI.queryDictItemsByCode(var10);
					}

					if (var11 != null) {
						var6.put(var8.getFieldName(), var11);
						var9.put("customRender", var8.getFieldName());
					}
				}
			}

			HashMap dataMap = new HashMap(1);
			dataMap.put("columns", var5);
			dataMap.put("dictOptions", var6);
			dataMap.put("cgreportHeadName", one.getName());
			return Result.ok(dataMap);
		}
	}

	@GetMapping({"/getData/{code}"})
	@PermissionData
	public Result<?> getData(@PathVariable("code") String var1, HttpServletRequest var2) {
		OnlCgreportHead var3 = (OnlCgreportHead) this.onlCgreportHeadService.getById(var1);
		if (var3 == null) {
			return Result.error("实体不存在");
		} else {
			String var4 = var3.getCgrSql().trim();
			String var5 = var3.getDbSource();

			try {
				Map var6 = DBSqlUtil.a(var2);
				var6.put("getAll", var2.getAttribute("getAll"));
				Map var7;
				if (StringUtils.isNotBlank(var5)) {
					a.info("Online报表: 走了多数据源逻辑");
					var7 = this.onlCgreportHeadService.executeSelectSqlDynamic(var5, var4, var6, var3.getId());
				} else {
					a.info("Online报表: 走了稳定逻辑");
					var7 = this.onlCgreportHeadService.executeSelectSql(var4, var3.getId(), var6);
				}

				return Result.ok(var7);
			} catch (Exception var8) {
				a.error(var8.getMessage(), var8);
				return Result.error("SQL执行失败：" + var8.getMessage());
			}
		}
	}

	@GetMapping({"/getQueryInfo/{code}"})
	public Result<?> b(@PathVariable("code") String var1) {
		try {
			List var2 = this.onlCgreportItemService.getAutoListQueryInfo(var1);
			return Result.ok(var2);
		} catch (Exception var3) {
			a.info(var3.getMessage(), var3);
			return Result.error("查询失败");
		}
	}

	@GetMapping({"/getParamsInfo/{code}"})
	public Result<?> c(@PathVariable("code") String var1) {
		try {
			LambdaQueryWrapper<OnlCgreportParam> var2 = new LambdaQueryWrapper();
			var2.eq(OnlCgreportParam::getCgrheadId, var1);
			List var3 = this.onlCgreportParamService.list(var2);
			return Result.ok(var3);
		} catch (Exception var4) {
			a.info(var4.getMessage(), var4);
			return Result.error("查询失败");
		}
	}

	@PermissionData
	@RequestMapping({"/exportXls/{reportId}"})
	public void exportXls(@PathVariable("reportId") String reportId, HttpServletRequest req, HttpServletResponse res) {
		String var4 = "报表";
		String var5 = "导出信息";
		if (!oConvertUtils.isNotEmpty(reportId)) {
			throw new AppException("参数错误");
		} else {
			Map var6 = null;

			try {
				var6 = this.onlCgreportHeadService.queryCgReportConfig(reportId);
			} catch (Exception var31) {
				throw new AppException("动态报表配置不存在!");
			}

			List var7 = (List) var6.get("items");
			req.setAttribute("getAll", true);
			Result var8 = this.getData(reportId, req);
			List records = null;
			if (var8.getCode().equals(200)) {
				Map var10 = (Map) var8.getResult();
				records = (List) var10.get("records");
			}

			ArrayList var32 = new ArrayList();

			String toStr;
			for (int i = 0; i < var7.size(); ++i) {
				if ("1".equals(oConvertUtils.getString(((Map) var7.get(i)).get("is_show")))) {
					toStr = ((Map) var7.get(i)).get("field_name").toString();
					ExcelExportEntity var13 = new ExcelExportEntity(((Map) var7.get(i)).get("field_txt").toString(), toStr, 15);
					Object dict_code = ((Map) var7.get(i)).get("dict_code");
					JSONArray jsonArray = JSONObject.parseArray(JSONObject.toJSONString(records));
					//构造字典的编码code
					List var16 = this.getDictList(oConvertUtils.getString(dict_code), jsonArray, toStr);
					if (var16 != null && var16.size() > 0) {
						ArrayList dicts = new ArrayList();
						Iterator iterator = var16.iterator();

						while (iterator.hasNext()) {
							DictModel dict = (DictModel) iterator.next();
							dicts.add(dict.getText() + "_" + dict.getValue());
						}

						var13.setReplace((String[]) dicts.toArray(new String[dicts.size()]));
					}

					Object var36 = ((Map) var7.get(i)).get("replace_val");
					if (oConvertUtils.isNotEmpty(var36)) {
						var13.setReplace(var36.toString().split(","));
					}

					var32.add(var13);
				}
			}

			res.setContentType("application/vnd.ms-excel");
			ServletOutputStream sops = null;

			try {
				toStr = BrowserUtils.checkBrowse(req);
				if ("MSIE".equalsIgnoreCase(toStr.substring(0, 4))) {
					res.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(var4, "UTF-8") + ".xls");
				} else {
					String var34 = new String(var4.getBytes("UTF-8"), "ISO8859-1");
					res.setHeader("content-disposition", "attachment;filename=" + var34 + ".xls");
				}

				Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams((String) null, var5), var32, records);
				sops = res.getOutputStream();
				workbook.write(sops);
			} catch (Exception var29) {
				var29.printStackTrace();
			} finally {
				try {
					if(sops != null){
						sops.flush();
						sops.close();
					}
				} catch (Exception var28) {
					var28.printStackTrace();
				}

			}

		}
	}

	/**
	 *
	 * @param code
	 * @return
	 */
	@GetMapping({"/getRpColumns/{code}"})
	public Result<?> getRpColumns(@PathVariable("code") String code) {
		LambdaQueryWrapper<OnlCgreportHead> wrapper = new LambdaQueryWrapper();
		wrapper.eq(OnlCgreportHead::getCode, code);
		OnlCgreportHead var3 = (OnlCgreportHead) this.onlCgreportHeadService.getOne(wrapper);
		if (var3 == null) {
			return Result.error("实体不存在");
		} else {
			QueryWrapper var4 = new QueryWrapper();
			var4.eq("cgrhead_id", var3.getId());
			var4.eq("is_show", 1);
			var4.orderByAsc("order_num");
			List var5 = this.onlCgreportItemService.list(var4);
			ArrayList newList = new ArrayList();
			HashMap hashMap = new HashMap();

			HashMap var10;
			for (Iterator iterator = var5.iterator(); iterator.hasNext(); newList.add(var10)) {
				OnlCgreportItem one = (OnlCgreportItem) iterator.next();
				var10 = new HashMap(3);
				var10.put("title", one.getFieldTxt());
				var10.put("dataIndex", one.getFieldName());
				var10.put("align", "center");
				String var11 = one.getFieldType();
				if ("Integer".equals(var11) || "Date".equals(var11) || "Long".equals(var11)) {
					var10.put("sorter", "true");
				}

				String code1 = one.getDictCode();
				if (oConvertUtils.isNotEmpty(code1)) {
					//2
					List var13 = this.getDictList(one.getDictCode(), (JSONArray) null, (String) null);
					hashMap.put(one.getFieldName(), var13);
					var10.put("customRender", one.getFieldName());
				}
			}

			HashMap var14 = new HashMap(1);
			var14.put("columns", newList);
			var14.put("dictOptions", hashMap);
			var14.put("cgRpConfigId", var3.getId());
			var14.put("cgRpConfigName", var3.getName());
			return Result.ok(var14);
		}
	}

	/**
	 * 测试链接数据库
	 * @param sourceModel
	 * @return
	 */
	@PostMapping({"/testConnection"})
	public Result testConnection(@RequestBody DynamicDataSourceModel sourceModel) {
		Connection conn = null;
		Result result = new Result();
		/* 代码扫描传入参数为明文，需改前端传入为加密字符，后端解密
		try {
			Result var4;
			try {
				Class.forName(sourceModel.getDbDriver());
				conn = DriverManager.getConnection(sourceModel.getDbUrl(), sourceModel.getDbUsername(), sourceModel.getDbPassword());
				result = Result.ok("数据库连接成功");
			} catch (ClassNotFoundException var17) {
				a.error(var17.toString());
				var4 = Result.error("数据库连接失败：驱动类不存在");
				return var4;
			} catch (Exception var18) {
				a.error(var18.toString());
				var4 = Result.error("数据库连接失败：" + var18.getMessage());
				return var4;
			}
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException var16) {
				a.error(var16.toString());
			}
		}*/
		return result;
	}
}
